package com.puccampinas.finalproject.core.util;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public final class ConfigurationProvider {

    private static ConfigurationProvider instance = new ConfigurationProvider();

    private Map<String, Properties> cache = new ConcurrentHashMap<String, Properties>();

    private String directory = "./";

    private ConfigurationProvider() {

    }

    public static ConfigurationProvider getInstance() {
        return instance;
    }

    public static void init(String directory) {
        instance.directory = directory;
    }
    
    public Properties getSmartProperty(String relativePath) {
        return getSmartProperty(relativePath, true);
        
    }
    
    public Properties getSmartProperty(String relativePath, boolean useCache) {

        Properties result = cache.get(relativePath);
        try {

            if (result == null || !useCache) {
                
                while (directory == null) {
                    Thread.sleep(1000);
                }
                
                result = new Properties();
                result.load(new FileReader(new File(directory, relativePath)));
                
                cache.put(relativePath, result);

            }
        } catch (FileNotFoundException e) {
            
        } catch (IOException e) {
            
        } catch (InterruptedException e) {
            
        }
        return result;
    }

    /**
     * @return the directory
     */
    public String getDirectory() {
        return directory;
    }
  
}
